package com.itheima.job.test07;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Properties;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class TCPServer {
    public static void main(String[] args) throws IOException {
        ServerSocket ss = new ServerSocket(12345);
        ThreadPoolExecutor pool = new ThreadPoolExecutor(
                5,
                10,
                3,
                TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(10),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.AbortPolicy()
        );
        while (true){
            Socket socket = ss.accept();
            pool.submit(new TCPServerTherad(socket));
        }


    }
}
class TCPServerTherad implements Runnable{
    private Socket socket;

    public TCPServerTherad(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        try {
            InputStream is = socket.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            FileReader fr = new FileReader("day15_inter\\prop.properties");
            Properties prop = new Properties();
            prop.load(fr);
            OutputStream os = socket.getOutputStream();
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os));
            String line;
            while ((line= br.readLine())!=null){
                String[] split = line.split("=");
                if (!prop.containsKey(split[0])){
                    bw.write("用户名不存在,我给你注册一个吧");
                    prop.put(split[0],split[1]);
                    prop.store(new FileWriter("day15_inter\\prop.properties"),null);
                }else if (split[1].equals(prop.getProperty(split[0]))){
                    bw.write("登录成功");
                }else {
                    bw.write("密码错误");
                }
            }
            bw.flush();
            socket.shutdownOutput();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
